package top.honlnk.service.impl.processor;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import top.honlnk.common.constant.AdminConstant;

import java.security.SecureRandom;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Slf4j
public class GenerateSubmissionIdProcessor {
    private static final String ALPHABET = "_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final SecureRandom RANDOM = new SecureRandom();
    private static final ZoneId BEIJING_ZONE_ID = ZoneId.of("Asia/Shanghai");

    public String encode() {
        long timestamp = System.currentTimeMillis() / 1000L; // Unix时间戳
        StringBuilder sb = new StringBuilder();
        while (timestamp != 0) {
            int remainder = (int) (timestamp % 26);
            sb.append(ALPHABET.charAt(remainder));
            timestamp /= 26;
        }

        sb.reverse();
        // 添加随机前缀
        // 生成两个随机的字符拼接在当前字符串的后
        String randomSuffix = getRandomSuffix();
        sb.append(randomSuffix);
        log.info(AdminConstant.TIMESTAMP_STRING, sb);
        return sb.toString();

    }

    // 将加密后的时间戳转成正常时间戳
    public LocalDate decode(String encodedTimestamp) {
        String timeStamp_26 = getTimeStamp_26(encodedTimestamp);
        long originalTimestamp = decodeBase26(timeStamp_26);
        return LocalDateTime.ofInstant(java.time.Instant.ofEpochSecond(originalTimestamp), BEIJING_ZONE_ID).toLocalDate();
    }

    // 将加密后的时间戳转成正常时间（精确到分钟）
    public LocalDateTime decodeToMinute(String encodedTimestamp) {
        String timeStamp_26 = getTimeStamp_26(encodedTimestamp);
        long originalTimestamp = decodeBase26(timeStamp_26);
        return LocalDateTime.ofInstant(java.time.Instant.ofEpochSecond(originalTimestamp), BEIJING_ZONE_ID).truncatedTo(java.time.temporal.ChronoUnit.SECONDS);
    }

    private @NotNull String getRandomSuffix() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 2; i++) {
            char randomChar = (char) ('A' + RANDOM.nextInt(26));
            sb.append(randomChar);
        }
        return sb.toString();
    }

    private @NotNull String getTimeStamp_26(String encodedTimestamp) {
        StringBuilder sb = new StringBuilder(encodedTimestamp);
        // 删除掉随机的两位后缀
        sb.delete(sb.length() - 2, sb.length());
//        sb.reverse();
        return sb.toString();
    }

    private long decodeBase26(@NotNull String base26String) {
        long decodedTimestamp = 0;
        for (int i = 0; i < base26String.length(); i++) {
            char c = base26String.charAt(i);
            int index = ALPHABET.indexOf(c);
            decodedTimestamp = decodedTimestamp * 26 + index;
        }
        return decodedTimestamp;
    }
}

